import os
import torch
import random
import pickle
import numpy as np
import torch.distributed as dist


'''setrandomseed'''
def setrandomseed(seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)


'''postprocesspredgtpairs'''
def postprocesspredgtpairs(all_preds, all_gts, cmd_args, cfg, logger_handle):
    # save results
    work_dir = cfg.SEGMENTOR_CFG['work_dir']
    filename = cfg.SEGMENTOR_CFG['resultsavepath'].split('/')[-1].split('.')[0] + cfg.SEGMENTOR_CFG['resultsavepath'].split('.')[-1]
    with open(os.path.join(work_dir, filename), 'wb') as fp:
        pickle.dump([all_preds, all_gts], fp)
    # post-process
    all_preds_gather, all_gts_gather = [], []
    fp = open(os.path.join(work_dir, filename), 'rb')
    all_preds, all_gts = pickle.load(fp)
    all_preds_gather += all_preds
    all_gts_gather += all_gts
    all_preds, all_gts = all_preds_gather, all_gts_gather
    all_preds_filtered, all_gts_filtered, all_ids = [], [], []
    for idx, pred in enumerate(all_preds):
        if pred[0] in all_ids:
            continue
        all_ids.append(pred[0])
        all_preds_filtered.append(pred[1])
        all_gts_filtered.append(all_gts[idx])
    all_preds, all_gts = all_preds_filtered, all_gts_filtered
    logger_handle.info('All Finished, all_preds: %s, all_gts: %s' % (len(all_preds), len(all_gts)))
    # return
    return all_preds, all_gts, all_ids
